package ct.zxd.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.bean.Cart;
import ct.zxd.db.TCartDao;
import net.sf.json.JSONArray;

public class HandleCart extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8;");
		PrintWriter pw = response.getWriter() ;
		
		String flag = request.getParameter("flag");
		String userId = request.getParameter("userId") ;
		Integer dishId =request.getParameter("dishId") != null ? Integer.parseInt(request.getParameter("dishId")) : 0 ;
		Integer number =request.getParameter("number") != null ? Integer.parseInt(request.getParameter("number")) : 0 ;
		Integer check =request.getParameter("check") != null ? Integer.parseInt(request.getParameter("check")) : 1  ;
		System.out.println("flag = " + flag );
		System.out.println("userId = " + userId);
		System.out.println("dishId = " + dishId);
		System.out.println("number = " + number);
		System.out.println("check = " + check);
		TCartDao tc = new TCartDao() ;
		List<Cart> cartList = new ArrayList<Cart> () ;
		
		try {
			if("add".equals(flag)) {
				 if(tc.selectDishByUserid(userId, dishId).getUserId() == null) {
					 pw.write(tc.insertCart(userId, dishId,number) > 0 ? "ok" : "no" ) ;
				 }else {
					 pw.write(tc.updateAgainNumber(userId, dishId, number) > 0 ? "ok" : "no");
				 }
			}else if("updateAdd".equals(flag)) {
				pw.write(tc.updateAddCartNumber(userId, dishId) > 0 ? "ok" : "no") ;
			}else if("updateDec".equals(flag)) {
				int count  = 0 ;
				count = tc.selectDishByUserid(userId, dishId).getNumber() ;
				System.out.println(count);
				if(count > 0) {
					pw.write(tc.updateDecCartNumber(userId, dishId) > 0 ? "ok" : "no") ;
				}else {
					pw.write("购物车数量商品数量不大于0");
				}
			}else if("check".equals(flag)) {
				pw.write(tc.updateCartCheck(dishId, check, userId) > 0 ? "ok" : "no");
			}else if("del".equals(flag)) {
				pw.write(tc.deleteCart(dishId, userId) > 0 ? "ok" : "no");
			}else if("all".equals(flag)){
				cartList = tc.selectCartsByUserId(userId) ;
				JSONArray array = JSONArray.fromObject(cartList);
				pw.print(array);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}
